package com.briup.demo.service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.briup.demo.bean.CmsArticle;
import com.briup.demo.bean.CmsCategory;
import com.briup.demo.mapper.CmsArticleMapper;
import com.briup.demo.mapper.CmsCategoryMapper;

@Service
public class CmsArticleService {
	
	@Autowired
	CmsArticleMapper articleMapper;
	
	@Autowired
	CmsCategoryMapper categoryMapper;
	
	public boolean updateState(String artId,String state) {
		int result = articleMapper.updateStateById(artId, state);
		//返回结果代表更新的记录条数，如果一条都没有，代表数据不存在。
		if(result==0) { 
			return false;
		}
		return true;
	}
	
	
	public List<CmsArticle> searchBy(
			Date begin,Date end,String key){
		return articleMapper.selectBy(begin, end, key);
	}
	
	
	
	public boolean saveOrUpdate(String id,String title,
			String author,String categoryId) {
		if(categoryId!=null&&!"".equals(categoryId)) {
			CmsCategory c = 
				categoryMapper.selectByPrimaryKey(categoryId);
			if(c==null) { //如果栏目为空，就代表栏目不存在，应该请用户重新选择栏目
				return false;
			}
		}
		//如果用户没有传递文章编号，代表需要插入文章信息
		if(id==null||"".equals(id)) {
			CmsArticle art = new CmsArticle();
			art.setId(UUID.randomUUID().toString());
			art.setTitle(title);
			art.setMemberName(author);
			art.setCategoryId(categoryId);
			art.setPublishDate(new Date());
			art.setStatus("待审核");
			art.setReadNum(0);
			articleMapper.insert(art);
		}else {
			//如果用户传递了文章编号，代表需要更新文章信息
			CmsArticle art = 
					articleMapper.selectByPrimaryKey(id);
			if(art==null) {
				return false;
			}
			art.setTitle(title);
			art.setCategoryId(categoryId);
			art.setMemberName(author);
			articleMapper.updateByPrimaryKey(art);
		}
		return true;
	}
	
	public int deleteById(String id) {
		return articleMapper.deleteByPrimaryKey(id);
	}
	
	public int deleteByIds(String[] ids) {
		int num = 0;
		for(String id:ids) {
			articleMapper.deleteByPrimaryKey(id);
			num++;
		}
		return num;
	}
	
	public List<CmsArticle> selectAll(){
		List<CmsArticle> list = articleMapper.selectAll();
		return list;
	}
	
}
